import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.time.LocalDateTime
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

fun adbShell(inCmd: String, deviceSN: String) {
    Run("adb -s $deviceSN shell $inCmd")
}

fun Run(inCmd: String, inWorkdir: String? = null) {
    Run(inCmd.split(" "), inWorkdir)
}

fun Run(inCmd: List<String>, inWorkdir: String? = null) {
    println("Run: $inCmd")
    val pb: ProcessBuilder = ProcessBuilder(inCmd)
            .directory(File(inWorkdir ?: "."))
            .redirectErrorStream(true)
    val p = pb.start()
    val reader = BufferedReader(InputStreamReader(p.inputStream))
    while (true) {
        val line = reader.readLine() ?: break
        println(line)
    }
    p.waitFor()
    if (0 != p.exitValue()) {
        throw RuntimeException()
    }
}

fun CheckOutput(inCmd: String, inWorkdir: String? = null): List<String> {
    return CheckOutput(inCmd.split(" "), inWorkdir)
}

fun CheckOutput(inCmd: List<String>, inWorkdir: String? = null): List<String> {
    println("Run: $inCmd")
    val ret = mutableListOf<String>()
    val pb: ProcessBuilder = ProcessBuilder(inCmd)
            .directory(File(inWorkdir ?: "."))
            .redirectErrorStream(true)
    val p = pb.start()
    val reader = BufferedReader(InputStreamReader(p.inputStream))
    while (true) {
        val line = reader.readLine() ?: break
        ret.add(line)
    }
    p.waitFor()
    if (0 != p.exitValue()) {
        throw RuntimeException()
    }
    return ret
}

fun isDeviceOnline(deviceSN: String): Boolean {
    var ret = false
    CheckOutput("adb devices").forEach {
        if (it.contains(deviceSN)) {
            ret = true
        }
    }
    return ret
}

fun isDeviceBootComplete(deviceSN: String): Boolean {
    val bootComp = CheckOutput("adb -s $deviceSN shell getprop sys.boot_completed")
    if (bootComp.size == 1 && bootComp[0] == "1") {
        return true
    }
    return false
}

fun inputText(text: String, delay: Long = 1) {
    text.toCharArray().forEach {
        adbShell("input text $it", deviceId)
        TimeUnit.SECONDS.sleep(delay)
    }
}

fun inputKeySequence(keys: Array<String>, delay: Long = 1) {
    keys.forEach {
        adbShell("input keyevent $it", deviceId)
        TimeUnit.SECONDS.sleep(delay)
    }
}

if (args.size != 1) {
    println("usage: prog <deviceId>")
    exitProcess(1)
}

val deviceId = args[0]

inputText("tester_syna_sqa13@netflix.com")
inputKeySequence(arrayOf<String>("DPAD_DOWN", "DPAD_DOWN","DPAD_DOWN","DPAD_CENTER"))
inputText("Synaptics88")
inputKeySequence(arrayOf<String>("DPAD_DOWN", "DPAD_DOWN","DPAD_DOWN","DPAD_DOWN","DPAD_DOWN","DPAD_CENTER"))
